﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;

namespace RESP_IIWaterAssessment
{
    public partial class CanalStateFormReport : Form
    {
        public CanalStateFormReport()
        {
            InitializeComponent();
        }

        int regID, avpID, kv, year;

        private void CanalStateFormReport_Load(object sender, EventArgs e)
        {
            cbRegion.SelectedIndexChanged -= cbRegion_SelectedIndexChanged;
            cbRegion.DataSource = UtilClass.FillCBRegions();
            cbRegion.DisplayMember = "Name";
            cbRegion.ValueMember = "ID";

            if (InformationClass.isAdmin)
            {
                cbRegion.SelectedIndex = -1;
                cbRegion.Text = string.Empty;
                cbRegion.SelectedIndexChanged += new EventHandler(cbRegion_SelectedIndexChanged);
            }
            else
            {
                
                cbRegion.Enabled = false;
                regID = InformationClass.regionID;
                cbRegion.SelectedIndexChanged += new EventHandler(cbRegion_SelectedIndexChanged);
                cbRegion.SelectedValue = regID;
                cbRegion_SelectedIndexChanged(cbRegion, null);
                cbAVP.Enabled = true;
                cbAVP.Text = string.Empty;
                //toolStrip1.Visible = false;
            }

            for (int i = 1991; i < 2100; i++)
            {
                cbYear.Items.Add(i);
            }
            cbYear.SelectedIndex = cbYear.FindStringExact(DateTime.Now.Year.ToString());
            year = Convert.ToInt32(cbYear.Text);
            for (int i = 0; i < 4; i++)
            {
                cbKvartal.Items.Add((i + 1).ToString() + " Квартал");
            }
            cbKvartal.SelectedIndex = 0;
        }

        private void cbAVP_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbAVP.SelectedIndex >= 0)
            {
                avpID = Convert.ToInt32(cbAVP.SelectedValue);
            }
        }

        private void cbRegion_SelectedIndexChanged(object sender, EventArgs e)
        {
            cbAVP.SelectedIndexChanged -= cbAVP_SelectedIndexChanged;
            regID = Convert.ToInt32(cbRegion.SelectedValue);
            cbAVP.DataSource = UtilClass.FillAVP(regID);
            cbAVP.DisplayMember = "Name";
            cbAVP.ValueMember = "ID";
            cbAVP.SelectedIndex = -1;
            cbAVP.Text = string.Empty;
            cbAVP.Enabled = true;
            cbAVP.SelectedIndexChanged += new EventHandler(cbAVP_SelectedIndexChanged);
        }

        private void cbKvartal_SelectedIndexChanged(object sender, EventArgs e)
        {
            kv = cbKvartal.SelectedIndex;
        }

        private void cbYear_SelectedIndexChanged(object sender, EventArgs e)
        {
            year = Convert.ToInt32(cbYear.Text);
        }

        private void buttonShow_Click(object sender, EventArgs e)
        {
            int? aID;
            DateTime? dt;

            if (chbAVP.Checked && avpID > 0)
                aID = avpID;
            else
                aID = null;

            if (chbKvartal.Checked && year > 0 && kv >= 0)
                dt = new DateTime(year, kv * 3 + 1, 1);
            else
                dt = null;

            dgvCanalState.DataSource = DBClass.RESPContext.CanalStateReport(aID, dt);

            if (InformationClass.Lang)
            {
                dgvCanalState.Columns["Date"].HeaderText = "Квартал";
                dgvCanalState.Columns["Name"].HeaderText = "Канал";
                dgvCanalState.Columns["ModernEquipment"].HeaderText = "Современная оснащенность средствами водоучета";
                dgvCanalState.Columns["WeirQuantity"].HeaderText = "Количество водосливов и насадок";
                dgvCanalState.Columns["SANIIRIQuantity"].HeaderText = "Количество лотков \"САНИИРИ\"";
                dgvCanalState.Columns["ChannelQuantity"].HeaderText = "Фиксированное русло";
                dgvCanalState.Columns["EquipmentNeed"].HeaderText = "Потребность в оснащении средствами водоучета, в ед.";
                dgvCanalState.Columns["WeirNeed"].HeaderText = "Потребность водосливов и насадок";
                dgvCanalState.Columns["SANIIRINeed"].HeaderText = "Потребность в лотках \"САНИИРИ";
                dgvCanalState.Columns["ChannelNeed"].HeaderText = "Потребность в фиксированных руслах";
                dgvCanalState.Columns["RailNeed"].HeaderText = "Потребность. Уровнемерные рейки,";
                dgvCanalState.Columns["ShieldNeed"].HeaderText = "Потребность. Регулирующие  затворы и щиты";
                dgvCanalState.Columns["BridgeNeed"].HeaderText = "Потребность. Гидрометрические  мостики";
            }
            else
            {
                dgvCanalState.Columns["Date"].HeaderText = "Чорак";
                dgvCanalState.Columns["Name"].HeaderText = "Канал";
                dgvCanalState.Columns["ModernEquipment"].HeaderText = "Замонавий сув ўлчаш воситалари билан жиҳозланганлиги, дона";
                dgvCanalState.Columns["WeirQuantity"].HeaderText = "Сув ташлаш иншоотлари ва насадкалар";
                dgvCanalState.Columns["SANIIRIQuantity"].HeaderText = "\"САНИИРИ\" лотоки";
                dgvCanalState.Columns["ChannelQuantity"].HeaderText = "Белгиланган ўзна";
                dgvCanalState.Columns["EquipmentNeed"].HeaderText = "Сув ўлчаш воситалари билан жиҳозлашга талаб, дона";
                dgvCanalState.Columns["WeirNeed"].HeaderText = "Сув ташлаш иншоотлари ва насадкалар жиҳозлашга талаб";
                dgvCanalState.Columns["SANIIRINeed"].HeaderText = "\"САНИИРИ лотоки жиҳозлашга талаб";
                dgvCanalState.Columns["ChannelNeed"].HeaderText = "Белгиланган ўзна жиҳозлашга талаб";
                dgvCanalState.Columns["RailNeed"].HeaderText = "Сатҳ ўлчаш рейкалари,дона/метр жиҳозлашга талаб";
                dgvCanalState.Columns["ShieldNeed"].HeaderText = "Ростловчи тамбалар ва қалқонлар жиҳозлашга талаб, дона ";
                dgvCanalState.Columns["BridgeNeed"].HeaderText = "Гидрометрик кўприкчалар жиҳозлашга талаб, дона";
            }

            for (int i = 0; i < dgvCanalState.RowCount; i++)
            {
                dgvCanalState.Rows[i].HeaderCell.Value = (i + 1).ToString();
            }

            dgvCanalState.AutoResizeColumns();
        }

        Sheets excelsheets;
        Worksheet excelworksheet;
        Microsoft.Office.Interop.Excel.Application excelapp;
        Workbook excelappworkbook;
        Workbooks excelappworkbooks;

        private void buttonExcel_Click(object sender, EventArgs e)
        {
            if (dgvCanalState.RowCount > 0)
            {
                MessageBox.Show(msgClass.msgWaiting);
                GetReport();

                excelworksheet.Select(8);
                excelapp.Visible = true;
            }
        }

        //private void GetReport()
        //{
        //    excelapp = new Microsoft.Office.Interop.Excel.Application();
        //    excelapp.SheetsInNewWorkbook = 1;

        //    if (InformationClass.Lang)
        //        excelapp.Workbooks.Open(System.Windows.Forms.Application.StartupPath + @"\Templates\i6r8.xls", false, true, Type.Missing, Type.Missing, Type.Missing, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
        //    else
        //        excelapp.Workbooks.Open(System.Windows.Forms.Application.StartupPath + @"\Templates\i6r8uz.xls", false, true, Type.Missing, Type.Missing, Type.Missing, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

        //    excelappworkbook = excelapp.Workbooks[1];
        //    excelsheets = excelappworkbook.Worksheets;// .Worksheets[0]; //Sheets 
        //    excelworksheet = (Microsoft.Office.Interop.Excel.Worksheet)excelsheets.get_Item(1);

        //    excelworksheet.Cells.NumberFormat = "@";

        //    if (chbKvartal.Checked)
        //    {
        //        excelworksheet.Cells[7, 2] = "Период: "+cbKvartal.Text+" "+cbYear.Text+"____года";
        //    }

        //    for (int i = 0; i < dgvCanalState.Rows.Count; i++)
        //    {
        //        for (int j = 1; j < dgvCanalState.Columns.Count; j++)
        //        {
        //            excelworksheet.Cells[i + 10, dgvCanalState.Columns[j].DisplayIndex + 2] = dgvCanalState[j, i].FormattedValue;
        //            addBorder(excelworksheet.Cells[i + 10, dgvCanalState.Columns[j].DisplayIndex + 2]);
        //        }

        //        //string avpName = UtilClass.GetAVPNameCanal((string)dgvCanalState["Name", i].Value).ToString();
        //        //excelworksheet.Cells[i + 9, 4] = avpName;
        //        //addBorder(excelworksheet.Cells[i + 9, 4]);
        //        //excelworksheet.Cells[i + 9, 3] = UtilClass.GetRegionName(avpName);
        //        //addBorder(excelworksheet.Cells[i + 9, 3]);
        //        excelworksheet.Cells[i + 10, 2] = i + 1;
        //        addBorder(excelworksheet.Cells[i + 10, 2]);
        //    }
        //    excelworksheet.Columns.AutoFit();
        //    excelworksheet.Rows.AutoFit();
        //}

        private void GetReport()
        {
            excelapp = new Microsoft.Office.Interop.Excel.Application();
            excelapp.SheetsInNewWorkbook = 1;

            if (InformationClass.Lang)
                excelapp.Workbooks.Open(System.Windows.Forms.Application.StartupPath + @"\Templates\i6r8.xls", false, true, Type.Missing, Type.Missing, Type.Missing, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            else
                excelapp.Workbooks.Open(System.Windows.Forms.Application.StartupPath + @"\Templates\i6r8uz.xls", false, true, Type.Missing, Type.Missing, Type.Missing, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

            excelappworkbook = excelapp.Workbooks[1];
            excelsheets = excelappworkbook.Worksheets;// .Worksheets[0]; //Sheets 
            excelworksheet = (Microsoft.Office.Interop.Excel.Worksheet)excelsheets.get_Item(1);

            excelworksheet.Cells.NumberFormat = "@";

            if (chbKvartal.Checked)
            {
                excelworksheet.Cells[7, 2] = "Период: " + cbKvartal.Text + " " + cbYear.Text + "года";
            }

            if (chbAVP.Checked)
            {
                excelworksheet.Cells[4, 3] = cbRegion.Text;
                excelworksheet.Cells[5, 3] = cbAVP.Text;
            }

            object[,] objData = new Object[dgvCanalState.Rows.Count, dgvCanalState.Columns.Count];
            for (int i = 0; i < dgvCanalState.Rows.Count; i++)
            {
                objData[i, 0] = i+1;
                for (int j = 1; j < dgvCanalState.Columns.Count; j++)
                    objData[i, j] = dgvCanalState[j, i].FormattedValue;
            }

            Range rng = excelworksheet.get_Range(excelworksheet.Cells[10, 2], excelworksheet.Cells[dgvCanalState.Rows.Count+9, dgvCanalState.Columns.Count + 1]);
            rng.Value2 = objData;
            rng.Borders[XlBordersIndex.xlEdgeLeft].LineStyle = XlLineStyle.xlContinuous;
            rng.Borders[XlBordersIndex.xlEdgeBottom].LineStyle = XlLineStyle.xlContinuous;
            rng.Borders[XlBordersIndex.xlEdgeRight].LineStyle = XlLineStyle.xlContinuous;
            rng.Borders[XlBordersIndex.xlEdgeTop].LineStyle = XlLineStyle.xlContinuous;
            rng.Borders[XlBordersIndex.xlInsideHorizontal].LineStyle = XlLineStyle.xlContinuous;
            rng.Borders[XlBordersIndex.xlInsideVertical].LineStyle = XlLineStyle.xlContinuous;

            excelworksheet.Columns.AutoFit();
            excelworksheet.Rows.AutoFit();
        }

        private void addBorder(object p)
        {
            Range tmpRange = excelworksheet.get_Range(p, p);
            tmpRange.Borders[XlBordersIndex.xlEdgeLeft].LineStyle = XlLineStyle.xlContinuous;
            tmpRange.Borders[XlBordersIndex.xlEdgeBottom].LineStyle = XlLineStyle.xlContinuous;
            tmpRange.Borders[XlBordersIndex.xlEdgeRight].LineStyle = XlLineStyle.xlContinuous;
            tmpRange.Borders[XlBordersIndex.xlEdgeTop].LineStyle = XlLineStyle.xlContinuous;
        }

        private void dgvCanalState_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (dgvCanalState.Columns.Contains("Date"))
            {
                if (e.ColumnIndex.Equals(dgvCanalState.Columns["Date"].Index) && e.Value != null)
                {
                    DateTime dt = Convert.ToDateTime(e.Value);
                    switch (dt.Month)
                    {
                        case 1:
                            e.Value = "1 Квартал";
                            break;
                        case 4:
                            e.Value = "2 Квартал";
                            break;
                        case 7:
                            e.Value = "3 Квартал";
                            break;
                        case 10:
                            e.Value = "4 Квартал";
                            break;
                        default:
                            e.Value = "Неверные данные";
                            break;
                    }
                    e.Value += " (" + dt.Year.ToString() + ")";
                }
            }
        }

        private void buttonPrint_Click(object sender, EventArgs e)
        {
            if (dgvCanalState.RowCount > 0)
                PrintDGV.Print_DataGridView(dgvCanalState);
        }
    }
}
